package net.simpleos;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpSession;

import net.simpleframework.organization.OrgUtils;
import net.simpleframework.util.AlgorithmUtils;
import net.simpleframework.util.HTTPUtils;
import net.simpleframework.web.page.IFilterListener;
import net.simpleframework.web.page.IPageConstants;
import net.simpleframework.web.page.PageParameter;
import net.simpleos.backend.permission.PermissionSession;
import net.simpleos.backend.permission.PlatformUtis;

/**
 * 
 * @author 李岩飞 
 * @email eliyanfei@126.com
 * @date 2014年11月30日 上午9:28:24 
 *
 */
public class SimpleosJobFilterListener implements IFilterListener {

	@Override
	public boolean doFilter(final PageParameter pageParameter, final FilterChain filterChain) throws IOException {
		final HttpSession httpSession = pageParameter.getSession();
		if (httpSession.getAttribute(IPageConstants.THROWABLE) != null) {
			return true;
		}
		if (SimpleosUtil.isManage(pageParameter) || !PlatformUtis.hasPermission) {
			return true;
		}
		PermissionSession permissionSession = PlatformUtis.DEFAULT_MENUS.get(pageParameter.getSession().getId());
		if (permissionSession == null) {
			permissionSession = new PermissionSession();
		}
		final Set<String> urlSet = new HashSet<String>(permissionSession.menuMap.values());

		final String url = HTTPUtils.getRequestURI(pageParameter.request);
		final String pre = pageParameter.getContextPath();
		if (url.contains(".html")
				&& !(url.contains("register.html") || url.contains("index.html") || url.contains("login.html") || url.contains("db.html") || url
						.contains("db.html"))) {
			if (!isPermission(urlSet, url, pre)) {
				pageParameter.loc(OrgUtils.deployPath + "jsp/job_http_access.jsp?v="
						+ AlgorithmUtils.base64Encode(HTTPUtils.getRequestAndQueryStringUrl(pageParameter.request).getBytes()) + "&job=manager");
				return false;
			}
		}
		return true;
	}

	public boolean isPermission(Set<String> urlSet, final String url, final String pre) {
		boolean flag = false;
		for (String menuUrl : urlSet) {
			if ((pre + menuUrl).startsWith(url)) {
				return true;
			}
		}
		return flag;
	}
}
